# coding=utf-8
"""
自动更新合并host文件
Filename: updateHosts.py
usage: python updateHosts.py
version: 13.6.18
"""
import urllib
import re,sys,os,time,platform

ip='127.0.0.1'
script_path=sys.argv[0]
script_dir=os.path.dirname(script_path)
hostsblock_dir=os.path.realpath(script_dir+os.sep+'hosts.block')
hosts_dir=os.path.realpath(script_dir+os.sep+'hosts')
white_file=os.path.join(script_dir,'whitehost.txt')
hosts_paths={'Windows'	: r'C:\WINDOWS\system32\drivers\etc\hosts',
			'Linux'		: '/etc/hosts'}
def get_files(_dir):
	_list=[]	
	for root, dirs, files in os.walk(_dir, topdown=False):
		for name in files:
			_file= os.path.join(root, name)
			_list.append(_file)
	return _list

def get_lines(file):
    _lines=['#host.block/'+os.path.basename(file)]
    _h=open(file,'r')
    for line in _h.readlines():
        line=line.strip()
        if in_white_list(line):
            continue
        if line!='':
            _lines.append(ip+'\t'+line)
    
    _h.close();
    return _lines

def get_white_list(file):
    _list=[]
    if os.path.isfile(file)==False:
        return _list
    f=open(file,'r')
    for line in f.readlines():
        line=line.strip()
        if line!='':
            _list.append(line)
    f.close();
    return _list

def in_white_list(host):
    global white_list
    return host in white_list

copy_str=""
for file in get_files(hosts_dir):
    copy_str=copy_str+'#host/'+os.path.basename(file)+'\n';
    copy_str=copy_str+open(file,'r').read(1024*1024)
    copy_str=copy_str+'\n'
 
white_list=get_white_list(white_file)
#print white_list


new_hosts=[]
for file in get_files(hostsblock_dir):
    print os.path.basename(file)
    new_hosts.extend(get_lines(file))
    new_hosts.extend('\n')
for line in new_hosts:
    print line

start_notice='#以下内容自动生成，修改后会自动覆盖\n\n'
_content=start_notice+copy_str+"\n".join(new_hosts)


start='#----ksc_start-----'
end  ='#----ksc_end-----'
_content=start+'\n'+_content+'\n'+end
hosts_path=hosts_paths[platform.system()]
hosts_out=hosts_path #r'D:\work\hosts\result.txt'


hosts_file= open(hosts_path,'r+')

lines = hosts_file.readlines()

need_insert= True
hosts_list=[]

is_filter=False
for i in lines:
    if(i.find('ksc_start')!=-1):
        hosts_list.append(_content+'\n')
        need_insert=False
        is_filter=True
    else:
        if is_filter:
            if(i.find('ksc_end')!=-1):#结束标记
                is_filter=True;
        else:
            hosts_list.append(i)
	
if need_insert:
    
    hosts_list.append(_content )
 
hosts_file.close()

hosts_file= open(hosts_out,'w')
hosts_file.write(''.join(hosts_list));
hosts_file.close()

print "success"
time.sleep(2)
